package com.fudan.backend.service.impl;

import com.fudan.backend.dao.CategoryDao;
import com.fudan.backend.exception.BaseException;
import com.fudan.backend.exception.RetCode;
import com.fudan.backend.pojo.Category;
import com.fudan.backend.service.CategoryService;
import com.fudan.backend.util.Snowflake;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    CategoryDao categoryDao;

    @Autowired
    Snowflake snowflake;

    @Override
    public Category getCategoryByCategoryId(String categoryId) {
        Category category = categoryDao.selectCategoryByCategoryId(categoryId);
        if(category == null){
            throw new BaseException(RetCode.CATEGORY_NOT_FOUND);
        }
        return category;
    }

    @Override
    public PageInfo<Category> getAllCategory(int current, int pageSize) {
        PageHelper.startPage(current, pageSize);
        List<Category> categories = categoryDao.selectAllCategory();
        return new PageInfo<Category>(categories, 5);
    }

    @Override
    public RetCode addCategory(Category category) {
        String categoryName = category.getCategoryName();
        int count = categoryDao.selectCategoryCountByCategoryName(categoryName);
        if(count != 0){
            return RetCode.CATEGORY_NAME_EXISTS;
        }
        category.setCategoryId((snowflake.nextId()).toString());
        categoryDao.insertCategory(category);
        return RetCode.CATEGORY_SUCCESS;
    }

    @Override
    public RetCode deleteCategory(String categoryId) {
        categoryDao.deleteCategory(categoryId);
        return RetCode.CATEGORY_SUCCESS;
    }

    @Override
    public RetCode updateCategory(Category category) {
        String categoryName = category.getCategoryName();
        int count = categoryDao.selectCategoryCountByCategoryName(categoryName);
        if(count != 0){
            return RetCode.CATEGORY_NAME_EXISTS;
        }
        categoryDao.updateCategory(category);
        return RetCode.CATEGORY_SUCCESS;
    }

    @Override
    public List<Category> getCategoryByPartialCategoryName(String categoryName) {
        List<Category> categories = categoryDao.selectCategoryByPartialCategoryName(categoryName);
        if(categories.size() == 0){
            throw new BaseException(RetCode.CATEGORY_NOT_FOUND);
        }
        return categories;
    }


}
